package main

import (
	"context"
	"fmt"
	"os"
	"os/signal"
	"regexp"
	"strconv"
	"syscall"
	"time"

	"gitee.com/simonxie979/skymeta/logutil"
	"gitee.com/simonxie979/skymeta/uuid"

	"github.com/joho/godotenv"
)

var (
	G_Context context.Context
	G_Cancel  context.CancelFunc

	NodeID uint16

	log *logutil.Logger
)

func main() {
	G_Context, G_Cancel = context.WithCancel(context.Background())

	if len(os.Args) < 2 {
		panic("config file not special")
	}

	if err := godotenv.Load(os.Args[1]); err != nil {
		panic(err)
	}

	init_Logger()

	log.Infof("Main", "os.Args: %v", os.Args)

	init_NodeID()
	init_UUID()

	LaunchNode()

	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT)

	ticker := time.NewTicker(time.Second * 3)

	for {
		select {
		case sig := <-sigChan:
			log.Errorf("Main", "recive signal %v. will quit the process.", sig)
			G_Cancel()
			exit()
			return
		case <-ticker.C:
			service.SendMsg()
		}
	}
}

func exit() {
	exit_Logger()
}

func init_NodeID() {
	str := os.Getenv("node_id")
	if !regexp.MustCompile(`^\d+$`).MatchString(str) {
		panic(fmt.Sprintf("invalid node_id: \"%s\"", str))
	}
	num, err := strconv.ParseUint(str, 10, 12)
	if err != nil {
		panic(err)
	}

	NodeID = uint16(num)
}

func init_UUID() {
	uuid.Init(NodeID)
}

// must initalization logger first
func init_Logger() {
	logPath := os.Getenv("log_path")
	logName := os.Getenv("log_name")
	logFormatter := os.Getenv("log_formatter")

	log = logutil.NewLogger(G_Context, logPath, logName, logFormatter)
	log.SetLevel(os.Getenv("log_level"))
}

// must exit logger last
func exit_Logger() {
	log.Wait()
}
